using AutoMapper;
using B.S.BaseData.Domain.Entities.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.ReadAPI.Applications.Commands.Users;
using B.S.BaseData.ReadAPI.Dtos.Users;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using LinqKit;

namespace B.S.BaseData.ReadAPI.Applications.Handlers.Users
{
    public class GetUserHandler : IRequestHandler<GetUserCommand, ApiResult<ApiPaging<GetUserReponseDto>>>
    {
        private readonly IUserRepository _userRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetUserHandler> _logger;

        public GetUserHandler(IUserRepository userRepository, IMapper mapper, ILogger<GetUserHandler> logger)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult<ApiPaging<GetUserReponseDto>>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var query = request.Query;
                // 动态拼接查询条件
                var predicate = PredicateBuilder.New<User>(true); // 初始条件，等价于 WHERE 1=1

                // 如果传了用户ID
                if (query.UserId > 0)
                    predicate = predicate.And(x => x.UserId == query.UserId);
                // 如果传了用户名
                if (!string.IsNullOrWhiteSpace(query.UserName))
                    predicate = predicate.And(x => x.UserName.Contains(query.UserName));
                // 如果传了手机号
                if (!string.IsNullOrWhiteSpace(query.Phone))
                    predicate = predicate.And(x => x.Phone == query.Phone);
                // 如果传了会员等级
                if (!string.IsNullOrWhiteSpace(query.MembershipLevel))
                    predicate = predicate.And(x => x.MembershipLevel == query.MembershipLevel);
                // 如果传了是否启用
                if (query.IsEnabled.HasValue)
                    predicate = predicate.And(x => x.IsEnabled == query.IsEnabled.Value);
                // 如果传了消费金额最小值
                if (query.ConsumptionAmountMin.HasValue)
                    predicate = predicate.And(x => x.ConsumptionAmount >= query.ConsumptionAmountMin.Value);
                // 如果传了消费金额最大值
                if (query.ConsumptionAmountMax.HasValue)
                    predicate = predicate.And(x => x.ConsumptionAmount <= query.ConsumptionAmountMax.Value);
                // 如果传了注册起始时间
                if (query.RegisterTimeStart.HasValue)
                    predicate = predicate.And(x => x.AddTime >= query.RegisterTimeStart.Value);
                // 如果传了注册结束时间
                if (query.RegisterTimeEnd.HasValue)
                    predicate = predicate.And(x => x.AddTime <= query.RegisterTimeEnd.Value);
                // 如果传了用户标签
                if (!string.IsNullOrWhiteSpace(query.UserTags))
                    predicate = predicate.And(x => x.UserTags == query.UserTags);
                // 如果传了注册渠道
                if (!string.IsNullOrWhiteSpace(query.RegistrationChannel))
                    predicate = predicate.And(x => x.RegistrationChannel == query.RegistrationChannel);

                var pageResult = await _userRepository.GetPageListAsync(query.pageIndex, query.pageSize, predicate);
                var dtoList = _mapper.Map<IList<GetUserReponseDto>>(pageResult.Data);
                var pagingDto = new ApiPaging<GetUserReponseDto>(pageResult.TotalCount, pageResult.TotalPage, dtoList);
                return ApiResult<ApiPaging<GetUserReponseDto>>.Success(pagingDto, StatusCodeEnum.Ok);

                /*
                // ======= 原有大Lambda查询代码，已注释保留 =======
                var pageResult = await _userRepository.GetPageListAsync(request.Query.pageIndex, request.Query.pageSize, x=> 
                    (x.UserId==request.Query.UserId||x.UserId==null) 
                    &&(x.UserName .Contains( request.Query.UserName)||x.UserName==null)
                    && (x.Phone== request.Query.Phone || x.Phone == null)
                    && (x.MembershipLevel == request.Query.MembershipLevel || x.MembershipLevel == null)
                    && (x.IsEnabled == request.Query.IsEnabled || x.IsEnabled == null)
                    && (x.ConsumptionAmount >= request.Query.ConsumptionAmountMin || x.ConsumptionAmount == null)
                    && (x.ConsumptionAmount <= request.Query.ConsumptionAmountMax || x.ConsumptionAmount == null)
                    && (x.AddTime >= request.Query.RegisterTimeStart || x.AddTime == null)
                    && (x.AddTime <= request.Query.RegisterTimeEnd || x.AddTime == null)
                    && (x.UserTags == request.Query.UserTags || x.UserTags == null)
                    && (x.RegistrationChannel == request.Query.RegistrationChannel || x.RegistrationChannel == null)
                );
                */
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户列表失败");
                return ApiResult<ApiPaging<GetUserReponseDto>>.Fail("获取用户列表失败", StatusCodeEnum.Exception);
            }
        }
    }
}